//
//  HomeTopBannerView.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2018/12/19.
//  Copyright © 2018 Gox_WallyDiao. All rights reserved.
//

import UIKit
import FSPagerView
import SDWebImage

protocol HomeTopBannerViewDelegate:NSObjectProtocol {
    func HomeTopBannerViewClick(clickUrl:String, target:String)
}

class HomeTopBannerView: UIView {
    weak var delegate:HomeTopBannerViewDelegate?
    
    var banner: [TopBannerImagesModel]?
    
    // MARK: - 懒加载滚动图片浏览器
    private lazy var pagerView : FSPagerView = {
        let pagerView = FSPagerView()
        pagerView.delegate = self
        pagerView.dataSource = self
        pagerView.automaticSlidingInterval =  3
        pagerView.isInfinite = true
        pagerView.interitemSpacing = 10
        pagerView.transformer = FSPagerViewTransformer(type: .linear)
        pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "HomeBannerCell")

        return pagerView
    }()
    
    var bannerList: [TopBannerImagesModel]? {
        didSet {
            guard let model = bannerList else { return }
            self.banner = model
            self.pagerView.reloadData()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(self.pagerView)
        self.pagerView.frame = frame
        self.pagerView.itemSize = CGSize.init(width: 285, height: 128)
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension HomeTopBannerView: FSPagerViewDelegate, FSPagerViewDataSource {
    // MARK:- FSPagerView Delegate
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.banner?.count ?? 0
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "HomeBannerCell", at: index)
        cell.imageView?.sd_setImage(with: URL(string:(StringIncludeChineseToString(self.banner?[index].pic ?? ""))), completed: nil)
        
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        let clickUrl:String = self.banner?[index].clickUrl ?? "0"
        let target:String = self.banner?[index].target ?? "0"
        delegate?.HomeTopBannerViewClick(clickUrl: clickUrl, target: target)
    }
}
